package com.redhat.auth.log.listener;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.dayatang.domain.InstanceFactory;
import com.redhat.auth.log.core.LogUser;


public class WebAppIntegrationFilter implements Filter {
	
	/**
	 * WebAppIntegrationFilter的init-param名称，此名称用于指定当前系统的名称，此参数可选
	 */
	public static final String INIT_PARAM_SYSTEM_NAME = "SYSTEM_NAME";
	
	protected static String systemName = null;
	
	private LogUser logUser;
	

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
	}

	public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		LogInfoUtil.setThreadLoalVariable(LogInfoUtil.SYSTEM_OPERATOR_KEY, getLogUser().getLoginUserName(httpRequest));
		// 设置系统地址
		if(LogInfoUtil.getGlobalVariable(LogInfoUtil.SYSTEM_ADDRESS_KEY)==null) {
			LogInfoUtil.setGlobalVariable(LogInfoUtil.SYSTEM_ADDRESS_KEY,httpRequest.getLocalAddr());
		}
		// 设置客户地址
		LogInfoUtil.setThreadLoalVariable(LogInfoUtil.CLIENT_ADDRESS_KEY, httpRequest.getRemoteAddr());
		filterChain.doFilter(request, response);
	}

	/**
	 * 过滤器初始化，从web.xml读取该过滤器的初始化参数：
	 * <li>OPERATOR_SESSION_KEY</li>
	 * <li>BIZ_SYSTEM_NAME</li>
	 */
	public final void init(FilterConfig filterConfig) throws ServletException {
		systemName = filterConfig.getInitParameter(INIT_PARAM_SYSTEM_NAME);
		LogInfoUtil.setGlobalVariable(LogInfoUtil.SYSTEM_NAME_KEY, systemName);
	}
	

	public LogUser getLogUser() {
		if(logUser==null){
			logUser = InstanceFactory.getInstance(LogUser.class);
		}
		return logUser;
	}

}
